package servlet;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import dao.CartDao;
import entity.Cart;
import entity.User;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/deleteCarts")
public class MyCartsDeleteServlet extends HttpServlet {
	@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");


		System.out.println("======deleteCarts====");
		// 获取请求中的cartIds参数
		String cartIdsJson = request.getParameter("cartIds");
		// 输出 cartIdsJson 以检查其内容
		System.out.println("Received cartIdsJson: " + cartIdsJson);

		if (cartIdsJson == null || cartIdsJson.isEmpty()) {
			response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write("{\"status\":\"error\", \"message\":\"cartIds parameter is missing or empty\"}");
			return;
		}

		// 使用Gson将JSON字符串转换为List<String>
		List<String> cartIds;
		try {
			Gson gson = new Gson();
			cartIds = gson.fromJson(cartIdsJson, List.class);
			// 输出解析后的 cartIds 以检查其内容
			System.out.println("Parsed cartIds: " + cartIds);
		} catch (JsonSyntaxException e) {
			e.printStackTrace();
			response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write("{\"status\":\"error\", \"message\":\"Invalid JSON format\"}");
			return;
		}
		CartDao dao = new CartDao();
		int ret = -1;
		for (String cartId : cartIds) {
			ret = dao.deleteByIdCart(Integer.valueOf(cartId));
		}
		if(ret == -1) {
			response.sendRedirect("error.jsp");
			return;
		}else {
			request.getSession().setAttribute("successMsg", "删除成功！");
			User user = (User) request.getSession().getAttribute("user");
			Integer userId = user.getUserId();
			List<Cart> myCartList = dao.selectMyCart(userId);
			request.getSession().setAttribute("myCartList",myCartList);
			// 返回响应
			response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			if (ret == 1) {
				response.getWriter().write("{\"status\":\"success\"}");
				System.out.println("{\"status\":\"success\"}");
			} else {
				response.getWriter().write("{\"status\":\"error\"}");
			}
		}
	}
}
